import sys
import cv2 as cv
import numpy as np


def my_project_match(imgori, imgtemp):
    # cv.imshow("orignal", imgori)
    # cv.imshow('template', imgtemp)
    global yloc
    global xloc
    global w
    global h

    print(type(imgori))
    print(type(imgtemp))
    result = cv.matchTemplate(imgori, imgtemp, cv.TM_CCOEFF_NORMED)
    # cv.imshow('result', result)
    minval, maxval, minloc, maxloc = cv.minMaxLoc(result)
    print(minval)
    print(maxval)
    print(minloc)
    print(maxloc)
    w = imgtemp.shape[1]
    h = imgtemp.shape[0]
    output = cv.rectangle(imgori, maxloc, (maxloc[0] + w, maxloc[1] + h), (0, 200, 0), 2)
    cv.imshow('output', output)

    threshold = .80
    yloc, xloc = np.where(result >= threshold)
    print(xloc)
    imgori_1 = imgori.copy()
    for (x, y) in zip(xloc, yloc):
        output1 = cv.rectangle(imgori_1, (x, y), (x + w, y + h), (0, 0, 222), 2)
        cv.imshow('output1', output1)


def only_one_rectangle(imgori):
    global yloc
    global xloc
    global w
    global h
    rectangles = []
    for (x, y) in zip(xloc, yloc):
        rectangles.append([int(x), int(y), int(w), int(h)])

    rectangles, weights = cv.groupRectangles(rectangles, 1, 0.2)
    print("蓝色方框数是", len(rectangles))

    for (x, y, w, h) in rectangles:
        output2 = cv.rectangle(imgori, (x, y), (x + w, y + h), (200, 0, 0), 2)
        cv.imshow('output2', output2)


def main_fuc(argv):
    imgori = cv.imread('images\\t001.jpg')
    assert imgori is not None, "图片读取失败，请检查路径"
    imgtemp = cv.imread('2.jpg')
    assert imgtemp is not None, "图片读取失败，请检查路径"
    my_project_match(imgori, imgtemp)
    only_one_rectangle(imgori)
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == '__main__':
    main_fuc(sys.argv)
